//用户浏览界面
package main

import (
	"io/ioutil"
	"log"
	"net/http"

	//"os"
	"path"
	"strconv"

	"github.com/russross/blackfriday"
)

type TreeViewdoc struct {
	Fid      int
	Title    string
	Backurl  string
	Prefix   string
	Pathname string
}
type TreeViewdoc2 struct {
	Fid                            int
	Logined                        bool
	Discuss                        []DiscusItem
	Recommand_count, Discuss_count int
	Prefix                         string
}

//HandleViewdoc 看文章，发评论、推荐
func (self *Site) HandleViewdoc(resp http.ResponseWriter, req *http.Request) {
	var tree1 TreeViewdoc
	tree1.Prefix = self.Prefix
	var tree2 TreeViewdoc2
	tree2.Prefix = self.Prefix
	var fid int
	_, err := req.Cookie("login")
	if err != nil {
		var discus1 http.Cookie
		discus1.Name = "login"
		discus1.Value = req.RemoteAddr
		http.SetCookie(resp, &discus1)
		//fmt.Println("add cookie")
	}
	_, err = req.Cookie("logined")
	if err == nil {
		tree2.Logined = true
	} else {
		tree2.Logined = false
	}
	//fmt.Println(tree2.Logined)
	fid, _ = strconv.Atoi(GetOne(req, "f"))
	tp1 := self.GetTitlePath(fid)
	if tp1 == nil {
		log.Println("error: GetTitlePath", fid)
		return
	}
	t1, err1 := self.OpenTemplateWithFuncs(path.Join("templates", "viewdoc.tmpl"), self.FuncMap)
	if err1 != nil {
		log.Println(err1)
		return
	}
	tree1.Title = tp1.Title
	tree1.Backurl = req.Referer()
	tree1.Fid = fid
	tree2.Fid = fid
	tree1.Prefix = self.Prefix
	tree2.Prefix = self.Prefix
	resp.WriteHeader(200)
	err1 = t1.ExecuteTemplate(resp, "t1", tree1)
	if err1 != nil {
		log.Println(err1)
	}

	resp.Write(ConvertMD(path.Join(self.DynBase, tp1.Pathname)))

	tree2.Discuss = self.GetDiscuss(fid, 10, 0)
	tree2.Recommand_count = tp1.Recommand_count
	tree2.Discuss_count = tp1.Discuss_count
	err1 = t1.ExecuteTemplate(resp, "t2", tree2)
	if err1 != nil {
		log.Println(err1)
	}
}

//ConvertMD 把markdown文本翻译成html
func ConvertMD(filename string) []byte {
	b1, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Println(err)
		return nil
	}
	r := blackfriday.HtmlRenderer(blackfriday.HTML_SKIP_HTML, "", "")
	opts := blackfriday.EXTENSION_FENCED_CODE | blackfriday.EXTENSION_TABLES
	return blackfriday.Markdown(b1, r, opts)
}

type BlockInfo1 struct {
	Bid   uint32
	Bname string
	Flist []FileList
}
type TreeIndex struct {
	Title    string
	Blocks   []BlockInfo1
	List0    []FileList
	ListTop1 []FileList
	ListTop2 []FileList
	ListTop3 []FileList
	Img      []ImgDoc
	Prefix   string
}

// 首页
func (self *Site) HandleIndex(resp http.ResponseWriter, req *http.Request) {
	var tree1 TreeIndex
	tree1.Prefix = self.Prefix
	tree1.Title = "文章列表"
	blks := self.GetBlocks()
	for _, v := range blks {
		var bi1 = new(BlockInfo1)
		bi1.Bid = v.Bid
		bi1.Bname = v.Name
		bi1.Flist = self.GetFilesByBID(v.Bid, 10, 0)
		tree1.Blocks = append(tree1.Blocks, *bi1)
		//fmt.Println(bi1.Bname)
	}
	tree1.List0 = self.GetFiles(12, 0)
	tree1.Img = self.GetImgDoc5()
	tree1.ListTop1 = self.GetRecommandTopN(6)
	tree1.ListTop2 = self.GetReadTopN(6)
	tree1.ListTop3 = self.GetDiscusTopN(6)
	resp.WriteHeader(200)
	err1 := self.ExecTemplateWithFuncs(path.Join("templates", "index.tmpl"), "",
		resp, tree1, self.FuncMap)
	if err1 != nil {
		log.Println(err1)
	}
}

type TreeBlocklist struct {
	Bname                        string
	Bid                          int
	Flist                        []FileList
	Blocks                       []Block
	Pn, Pn_pre, Pn_next, Pn_last int
	Prefix                       string
}

//板块视图，分页列表
func (self *Site) HandleBlocklist(resp http.ResponseWriter, req *http.Request) {
	var tree1 TreeBlocklist
	tree1.Prefix = self.Prefix
	// psize1:每页显示的文章数量
	var psize1 int = 20
	var pcount1 int
	// blockid
	var bid, pn int
	var err error
	bid, err = strconv.Atoi(GetOne(req, "b"))
	if err != nil {
		bid = 0
	}
	tree1.Bname = self.GetBlockName(uint32(bid))
	if len(tree1.Bname) == 0 {
		tree1.Bname = "全部"
	}
	tree1.Bid = bid
	// page number
	pn, err = strconv.Atoi(GetOne(req, "p"))
	if err != nil {
		pn = 1
	}
	if pn < 1 {
		pn = 1
	}
	count1 := self.GetCountByBID(bid)
	// calculate pages
	tree1.Pn = pn
	tree1.Pn_pre = pn - 1
	pcount1 = count1 / psize1
	if count1%psize1 > 0 {
		pcount1++
	}
	tree1.Pn_last = pcount1
	if pcount1 > tree1.Pn {
		tree1.Pn_next = tree1.Pn + 1
	} else {
		tree1.Pn_next = tree1.Pn
	}
	// Blocks
	tree1.Blocks = self.GetBlocks()
	// Flist
	//fmt.Println(bid,psize1)
	tree1.Flist = self.GetFilesByBID(uint32(bid), uint32(psize1), uint32((pn-1)*psize1))
	// show
	resp.WriteHeader(200)
	err1 := self.ExecTemplateWithFuncs(path.Join("templates", "blocklist.tmpl"), "", resp, tree1, self.FuncMap)
	if err1 != nil {
		log.Println(err1)
	}
}

type TreeSearch struct {
	K                            string
	Flist                        []FileList
	Pn, Pn_pre, Pn_next, Pn_last int
	Prefix                       string
}

func (self *Site) HandleSearch(resp http.ResponseWriter, req *http.Request) {
	var tree1 TreeSearch
	tree1.Prefix = self.Prefix
	tree1.K = GetOne(req, "k")
	var pn int
	var err error
	pn, err = strconv.Atoi(GetOne(req, "p"))
	if err != nil {
		pn = 1
	}
	if pn == 0 {
		pn = 1
	}
	var psize1 int = 20
	tree1.Flist = self.SearchFiles(tree1.K, psize1, (pn-1)*psize1)
	count1 := self.SearchCount(tree1.K)
	// calculate pages
	tree1.Pn = pn
	tree1.Pn_pre = pn - 1
	pcount1 := count1 / psize1
	if count1%psize1 > 0 {
		pcount1++
	}
	tree1.Pn_last = pcount1
	if pcount1 > tree1.Pn {
		tree1.Pn_next = tree1.Pn + 1
	} else {
		tree1.Pn_next = tree1.Pn
	}
	//render
	resp.WriteHeader(200)
	err1 := self.ExecTemplateWithFuncs(path.Join("templates", "search.tmpl"), "", resp, tree1, self.FuncMap)
	if err1 != nil {
		log.Println(err1)
	}
}

// ajax 推荐
func (self *Site) HandleRecommand(resp http.ResponseWriter, req *http.Request) {
	var fid int
	var err error
	fid, err = strconv.Atoi(GetOne(req, "f"))
	if err == nil {
		self.RecommandDoc(fid)
		resp.WriteHeader(200)
		resp.Write([]byte("感谢推荐"))
	}
}

type TreeDiscus struct {
	Fid                          int
	Title                        string
	Discuss                      []DiscusItem
	Pn, Pn_pre, Pn_next, Pn_last int
	Prefix                       string
}

// 分页显示全部评论
func (self *Site) HandleDiscussions(resp http.ResponseWriter, req *http.Request) {
	var tree1 TreeDiscus
	tree1.Prefix = self.Prefix
	fid, err := strconv.Atoi(GetOne(req, "f"))
	if err != nil {
		resp.WriteHeader(400)
		resp.Write([]byte("文件不存在"))
		return
	}
	if fid < 1 {
		resp.WriteHeader(400)
		resp.Write([]byte("文件不存在"))
		return
	}
	tree1.Fid = fid
	tree1.Title = self.GetTitleByFID(fid)
	// 分页显示
	var psize1 int = 20
	var pcount1, pn int
	pn, err = strconv.Atoi(GetOne(req, "p"))
	if err != nil {
		pn = 1
	} else if pn < 1 {
		pn = 1
	}
	tree1.Discuss = self.GetDiscuss(fid, psize1, (pn-1)*psize1)
	count1 := self.GetDiscusCount(fid)
	//计算分页数
	pcount1 = count1 / psize1
	if count1%psize1 > 0 {
		pcount1++
	}
	tree1.Pn = pn
	tree1.Pn_pre = pn - 1
	tree1.Pn_last = pcount1
	if pcount1 > tree1.Pn {
		tree1.Pn_next = tree1.Pn + 1
	} else {
		tree1.Pn_next = tree1.Pn
	}
	// show
	resp.WriteHeader(200)
	err1 := self.ExecTemplateWithFuncs(path.Join("templates", "discussions.tmpl"), "", resp, tree1, self.FuncMap)
	if err1 != nil {
		log.Println(err1)
	}
}
